package gupao.concurrency.threadpool.futures;

import gupao.concurrency.utils.ThreadPoolService;
import gupao.concurrency.utils.Utils;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class CannotCancelSample {

    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor executor = ThreadPoolService.getOrCreateThreadPoolExecutor(
                "test",4,4);
        boolean stop = false;
        AtomicBoolean started = new AtomicBoolean(false);
        CountDownLatch latch = new CountDownLatch(1);
        Future<?> f = executor.submit(() -> {
            while(!stop){
                try {
                    TimeUnit.MILLISECONDS.sleep(2000);
                    log.info("任务一还在继续运行");
                    started.compareAndSet(false, true);
                } catch (InterruptedException e) {
                    log.error("中断异常，忽略");
                }
            }
            latch.countDown();
            return "Finished";
        });
        while(!started.get()){
            Thread.yield();
        }
        log.info("cancel(true)一次..");
        f.cancel(true);
        log.info("等待任务一完成");
        Utils.sleepIgnoreExp(3000);
        log.info("cancel(false)一次..");
        f.cancel(false);
        latch.await();
    }
}
